package com.linkhub.oms.admin.modules.track.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.linkhub.oms.admin.modules.track.domain.request.TrackRequest;
import com.linkhub.oms.admin.modules.track.enums.TrackNotifyEventEnum;
import com.linkhub.oms.common.enums.mp.EmployeeBusinessStatusEnum;
import com.linkhub.oms.common.util.CacheKeyAssist;
import com.linkhub.oms.component.redis.locker.DistributedLocker;
import com.linkhub.oms.dao.mpservice.IOrderService;
import com.linkhub.oms.entity.OrderEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author Jaycle
 * @version 1.0.0
 * @Description WebhookServiceImpl.java
 * @createTime 2024/10/11 23:28
 */
@Slf4j
@Service
public class WebhookServiceImpl implements WebhookService {

    @Value("${track.key}")
    private String trackKey;
    @Resource
    private IOrderService orderService;
    @Resource
    private OrderTrackBizService orderTrackBizService;
    @Resource
    private DistributedLocker distributedLocker;

    @Override
    public void saveNotify( String body, String sign ) {
        String generatedSignature = getGeneratedSignature(body, trackKey);
        if (!generatedSignature.equals(sign)) {
            log.info("签名：{}与Shipo签名不匹配 {}", sign, generatedSignature);
            return;
        }
        JSONObject request = JSON.parseObject(body);
        TrackNotifyEventEnum event = request.getObject("event", TrackNotifyEventEnum.class);
        TrackRequest trackRequest = request.getObject("data",TrackRequest.class);
        OrderEntity orderEntity = orderService.getByWayBillNumber(trackRequest.getNumber());
        if (orderEntity == null) {
            log.info("运单不存在，运单号:{}", trackRequest.getNumber());
            return;
        }
        if (!Objects.equals(orderEntity.getEmployeeBusinessStatus(), EmployeeBusinessStatusEnum.TRACKING)) {
            log.info("运单不在追踪中，运单号:{}", trackRequest.getNumber());
            return;
        }
        String lockKey = CacheKeyAssist.getTrackEventNotifyLocKey(trackRequest.getNumber());
        try{
            if (!distributedLocker.tryLock(lockKey,1,3, TimeUnit.MINUTES)) {
                log.info("运单:{}追踪事件同步已加锁：{}，", trackRequest.getNumber(),lockKey);
                return;
            }
            TrackRequest.TrackInfo trackInfo = trackRequest.getTrackInfo();
            if(TrackNotifyEventEnum.TRACKING_UPDATED.equals(event)&&trackInfo!=null){
                orderTrackBizService.saveOrderTrackInfo(trackRequest,orderEntity);
            }
        }finally {
            distributedLocker.unlock(lockKey);
        }
    }

    /**
     * requestText {String} 原始通知报文
     * key         {String} 密钥
     * return      {String} 生成签名内容
     */
    private String getGeneratedSignature( String requestText, String key ) {
        try {
            String src = requestText + "/" + key;

            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hash = md.digest(src.getBytes(StandardCharsets.UTF_8));

            BigInteger number = new BigInteger(1, hash);
            StringBuilder hexString = new StringBuilder(number.toString(16));
            while(hexString.length() < 64) {
                hexString.insert(0, '0');
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
        }
        return "";
    }
}
